import math
import random
# 加载Wine数据，这里假设数据文件名为'wine.data'，每行格式为特征值用逗号分隔，最后一个是类别标签def load_wine_data():
def load_wine_data():
    data = []
    with open('C:/Users/admin/PycharmProjects/wine.data', 'r') as file:
        for line in file.readlines():
            row = line.strip().split(',')
            data.append(row)
    return data
# 划分训练集和测试集
def split_data(data, split_ratio=0.7):
    random.shuffle(data)
    train_size = int(len(data) * split_ratio)
    train_data = data[:train_size]
    test_data = data[train_size:]
    return train_data, test_data
# 计算欧几里得距离
def euclidean_distance(sample1, sample2):
    distance = 0
    for i in range(len(sample1) - 1):
        distance += (float(sample1[i]) - float(sample2[i])) ** 2
    return math.sqrt(distance)
# 获取k个最近邻
def get_neighbors(train_data, test_sample, k):
    distances = []
    for train_sample in train_data:
        dist = euclidean_distance(train_sample, test_sample)
        distances.append((train_sample, dist))
    distances.sort(key=lambda x: x[1])
    neighbors = [distances[i][0] for i in range(k)]
    return neighbors
# 根据邻居投票预测类别
def predict_class(neighbors):
    class_votes = {}
    for neighbor in neighbors:
        class_label = neighbor[-1]
        if class_label in class_votes:
            class_votes[class_label] += 1
        else:
            class_votes[class_label] = 1
    sorted_votes = sorted(class_votes.items(), key=lambda x: x[1], reverse=True)
    return sorted_votes[0][0]
# 评估模型准确率
def evaluate_model(train_data, test_data, k):
    correct_predictions = 0
    for test_sample in test_data:
        neighbors = get_neighbors(train_data, test_sample, k)
        predicted_class = predict_class(neighbors)
        if predicted_class == test_sample[-1]:
            correct_predictions += 1
    accuracy = correct_predictions / len(test_data)
    return accuracy
if __name__ == "__main__":
    wine_data = load_wine_data()
    train_data, test_data = split_data(wine_data)
    k = 5  # 可以自行调整k值
    accuracy = evaluate_model(train_data, test_data, k)
    print(f"Accuracy: {accuracy}")